<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">
          {{getTitleByName(nameOfPermission)}}列表查询
          <el-button link @click="delFav()" style="margin-bottom: 5px;" v-if="userFavorites?.length > 0">
            <svg-icon icon-class="stars" color="#E6A23C" />
          </el-button>
          <el-button link @click="addFav()" style="margin-bottom: 5px;" v-else>
            <svg-icon icon-class="star" />
          </el-button>
        </div>
        <div>
          <el-button v-waves type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
        </div>
      </el-col>
    </el-row>
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline">
        <el-form-item prop="expenditureKpiId" label="指标单">
          <el-select v-model="listQuery.expenditureKpiId" class="m-2" placeholder="请选择" clearable filterable>
            <el-option key="" label="全部" value="" />
            <el-option v-for="item in expenditureKpiList" :key="item.id" :label="`${item.kpiCode} - ${item.kpiName}`" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="quotaCode" label="额度下达单编码">
          <InputTagDialog v-model="listQuery.quotaCode" placeholder="额度下达单编码" title="填写额度下达单编码" />
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker v-model="listQuery.quotaDateRange"
                          value-format="YYYY-MM-DD"
                          style="width: 300px"
                          type="daterange"
                          range-separator="-"
                          start-placeholder="日期开始"
                          end-placeholder="日期结束" />
        </el-form-item>
        <el-form-item prop="kpi" label="预算指标">
          <el-input v-model="listQuery.kpi" placeholder="预算指标" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="submitOrganizationId" label="填单人部门">
          <Organization v-model="listQuery.submitOrganizationId" keyName="id" keyShow="organizationName" placeholder="申请人部门" title="部门查询" :disabled="useUserStore().organization.organizationType !== '1'" />
        </el-form-item>
        <el-form-item prop="submitUserId" label="填单人用户">
          <User v-model="listQuery.submitUserId" keyName="id" keyShow="name" placeholder="用户" title="用户查询" :disabled="useUserStore().organization.organizationType !== '1'" />
        </el-form-item>
        <!--
        <el-form-item prop="amount" label="额度下达初始化金额">
          <el-input v-model="listQuery.amount" placeholder="额度下达初始化金额" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="expenditureFiscalId" label="财政项目ID">
          <el-input v-model="listQuery.expenditureFiscalId" placeholder="项目" @keyup.enter="handleFilter" />
        </el-form-item>
        -->
      </el-form>
    </div>
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">列表详情</div>
        <div>
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Download" @click="handleExport">
            导出
          </el-button>
          <el-button type="primary" icon="Edit" :disabled="!checkAuthByCode('')" @click="handleAdd">
            新增
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-divider class="el-divider--horizontal-margin" />
    <el-table v-loading="listLoading"
              :key="tableKey"
              :data="list"
              :row-style="{height: '0'}"
              :cell-style="{padding: '0'}"
              border
              fit
              highlight-current-row
              tooltip-effect="dark"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="39px" />
      <el-table-column align="center" type="index" label="序号" width="60px" />
      <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="指标单编码" prop="expenditureKpiId" min-width="200px">
        <template v-slot="{row}">{{ getIdLabel(expenditureKpiList, row.expenditureKpiId, 'kpiCode') }}</template>
      </el-table-column>
      <el-table-column align="center" label="指标单名称" prop="expenditureKpiId" min-width="200px" show-overflow-tooltip>
        <template v-slot="{row}">{{ getIdLabel(expenditureKpiList, row.expenditureKpiId, 'kpiName') }}</template>
      </el-table-column>
      <el-table-column align="center" label="额度下达单编码" prop="quotaCode" min-width="180px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><CodeTag :code="row.quotaCode" /></template>
      </el-table-column>
      <el-table-column align="center" label="日期" prop="quotaDate" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.quotaDate?.substring(0, 10) }}</template>
      </el-table-column>
      <el-table-column align="center" label="预算指标" prop="kpi" min-width="105px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.kpi }}</template>
      </el-table-column>
      <el-table-column align="center" label="填单人部门" prop="submitOrganizationId" min-width="160px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="organizationList" :foreignIds="row.submitOrganizationId" :foreignLabel="'organizationName'" /></template>
      </el-table-column>
      <el-table-column align="center" label="填单人用户" prop="submitUserId" min-width="160px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="userList" :foreignIds="row.submitUserId" :foreignLabel="'name'" /></template>
      </el-table-column>
      <el-table-column align="center" label="额度下达初始化金额" prop="amount" min-width="180px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><MoneyTag :money="row.amount" /></template>
      </el-table-column>
      <el-table-column align="center" label="财政项目" prop="expenditureFiscalId" min-width="160px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ getIdLabel(expenditureFiscalList, row.expenditureFiscalId, 'name') }}</template>
      </el-table-column>
      <el-table-column align="center" label="摘要" prop="summary" min-width="80px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.summary }}</template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="160px" fixed="right">
        <template v-slot="{row}">
          <el-button type="primary" link @click="handleView(row)">查看</el-button>
          <el-button v-show="checkAuthByCode('')" type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-popconfirm confirm-button-text="确定"
                         cancel-button-text="取消"
                         :icon="WarningFilled"
                         icon-color="#626AEF"
                         title="您确定删除么？"
                         @confirm="handleDelete(row)"
                         v-if="checkAuthByCode('')">
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" />
    <el-dialog v-model="dialogVisible" :title="dialogTypeTitle" width="70%" top="2vh">
      <!--
      <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" :disabled="dialogType === 'view'" label-width="auto">
        <el-form-item v-show="isDebug" label="ID">
          <text>{{ obj.id }}</text>
        </el-form-item>
        <el-form-item label="指标单ID" prop="expenditureKpiId">
          <el-input v-model="obj.expenditureKpiId" type="number" placeholder="请输入指标单ID" />
        </el-form-item>
        <el-form-item label="额度下达单编码" prop="quotaCode">
          <el-input v-model="obj.quotaCode" placeholder="请输入额度下达单编码，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="日期" prop="quotaDate">
          <el-date-picker v-model="obj.quotaDate" placeholder="请输入日期" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="预算指标" prop="kpi">
          <el-input v-model="obj.kpi" placeholder="请输入预算指标，最多输入200个字符" />
        </el-form-item>
        <el-form-item label="填单人部门" prop="submitOrganizationId">
          <el-input v-model="obj.submitOrganizationId" type="number" placeholder="请输入填单人部门" />
        </el-form-item>
        <el-form-item label="填单人用户" prop="submitUserId">
          <el-input v-model="obj.submitUserId" type="number" placeholder="请输入填单人用户" />
        </el-form-item>
        <el-form-item label="额度下达初始化金额" prop="amount">
          <el-input-number v-model="obj.amount" placeholder="请输入额度下达初始化金额" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="财政项目ID" prop="expenditureFiscalId">
          <el-input v-model="obj.expenditureFiscalId" placeholder="请输入项目，最多输入200个字符" />
        </el-form-item>
        <el-form-item label="摘要" prop="summary">
          <el-input v-model="obj.summary" :autosize="{ minRows: 2, maxRows: 5}" type="textarea" class="textarea-1" />
        </el-form-item>
        <el-form-item label="创建时间">
          <text>{{ obj.createTime ? obj.createTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item label="最后修改时间">
          <text>{{ obj.updateTime ? obj.updateTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item v-show="isDebug" label="数据版本">
          <text>{{ obj.version }}</text>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="info" icon="Close" @click="dialogVisible=false">关闭</el-button>
        <el-button type="primary" icon="Check" v-show="dialogType !== 'view'" @click="doConfirm('obj')">确定</el-button>
      </div>
      -->
    </el-dialog>
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doGet, doPost, doPut, doDelete, doGetDownload} from '@/config/http'
import {alertErrorMsg, customValidator, getListPageSize, notifySuccess} from '@/config/common'
import useUserStore from "@/store/modules/user";
import {getUserId} from "@/config/cookie";
import SvgIcon from "@/components/SvgIcon/index.vue";
import InputTagDialog from "@/components/InputTag/inputTagDialog.vue";
import User from "@/views/components/base/selectUser.vue";
import Organization from "@/views/components/base/selectOrganization.vue";
import initListStore from '@/store/modules/initList'

const emptyObj = {
  expenditureKpiId: null, // 指标单ID
  quotaCode: null, // 额度下达单编码
  quotaDate: null, // 日期
  kpi: null, // 预算指标
  submitOrganizationId: null, // 填单人部门
  submitUserId: null, // 填单人用户
  amount: null, // 额度下达初始化金额
  expenditureFiscalId: null, // 财政项目ID
  summary: null, // 摘要
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
}

export default {
  name: 'expenditureInitQuota_nocache',
  components: {Organization, User, InputTagDialog, SvgIcon},
  mixins: [baseConfig],
  data() {
    return {
      svc: 'icims-api',
      obj: Object.assign({}, emptyObj),
      routes: [],
      dialogVisible: false,
      dialogType: 'add',
      dialogTypeTitle: '新增',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        sortField: 'id',
        sortType: 'desc',
        expenditureKpiId: null,
        quotaCode: null,
        quotaDateStart: null,
        quotaDateEnd: null,
        kpi: null,
        submitOrganizationId: useUserStore().organization.organizationType !== '1' ? useUserStore().organization.id : '',
        submitUserId: useUserStore().organization.organizationType !== '1' ? getUserId() : '',
        amount: null,
        expenditureFiscalId: null,
        createTimeStart: null,
        createTimeEnd: null,
        updateTimeStart: null,
        updateTimeEnd: null,
        quotaDateRange: [],
      },
      selectionList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        expenditureKpiId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '指标单ID', trigger: ['blur', 'change'] }],
        quotaCode: [{ required: false, validator: customValidator, min: 0, max: 100, label: '额度下达单编码', trigger: ['blur', 'change'] }],
        quotaDate: [{ required: false, validator: customValidator, min: 0, max: 20, label: '日期', trigger: ['blur', 'change'] }],
        kpi: [{ required: false, validator: customValidator, min: 0, max: 200, label: '预算指标', trigger: ['blur', 'change'] }],
        submitOrganizationId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '填单人部门', trigger: ['blur', 'change'] }],
        submitUserId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '填单人用户', trigger: ['blur', 'change'] }],
        amount: [{ required: false, validator: customValidator, min: 0, max: 13, label: '额度下达初始化金额', trigger: ['blur', 'change'] }],
        expenditureFiscalId: [{ required: false, validator: customValidator, min: 0, max: 200, label: '财政项目ID', trigger: ['blur', 'change'] }],
        summary: [{ required: false, validator: customValidator, min: 0, max: 0, label: '摘要', trigger: ['blur', 'change'] }],
      },
      governmentList: initListStore().governmentList,
      organizationList: initListStore().organizationList,
      userList: initListStore().userList,
      expenditurePtypeList: initListStore().expenditurePtypeList,//项目类型
      expenditureFunctionalList: initListStore().expenditureFunctionalList,//功能分类
      expenditureEconomicList:initListStore().expenditureEconomicList,//经济分类
      expenditureFiscalList: initListStore().expenditureFiscalList,//财政项目
      expenditureSubjectList: initListStore().expenditureSubjectList,//会计科目
      expenditureKpiList: initListStore().expenditureKpiList,//指标单
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    this.nameOfPermission = 'expenditureInitQuota'
    this.getFavorite(this.nameOfPermission)?.then(res => this.userFavorites = res)
    this.getList()
    // this.initList()
  },
  methods: {
    useUserStore,
    // async initList() {
    //   let p1 = doGet(this.svc, '/government/page', {pageSize: getListPageSize()}, false)
    //   let p2 = doGet(this.svc, '/organization/page', {pageSize: getListPageSize()}, false)
    //   let p3 = doGet(this.svc, '/user/page', {pageSize: getListPageSize()}, false)
    //   let p4 = doGet(this.svc, '/expenditure-ptype/page', {pageSize: getListPageSize()}, false)
    //   let p5 = doGet(this.svc, '/expenditure-functional/page', {pageSize: getListPageSize()}, false)
    //   let p6 = doGet(this.svc, '/expenditure-economic/page', {pageSize: getListPageSize()}, false)
    //   let p7 = doGet(this.svc, '/expenditure-fiscal/page', {pageSize: getListPageSize()}, false)
    //   let p8 = doGet(this.svc, '/expenditure-subject/page', {pageSize: getListPageSize()}, false)
    //   let p9 = doGet(this.svc, '/expenditure-kpi/page', {pageSize: getListPageSize()}, false)
    //   let resArray = await Promise.all([p1, p2, p3, p4, p5, p6, p7, p8, p9])
    //   this.governmentList = resArray[0]['records']
    //   this.organizationList = resArray[1]['records']
    //   this.userList = resArray[2]['records']
    //   this.expenditurePtypeList = resArray[3]['records']
    //   this.expenditureFunctionalList = resArray[4]['records']
    //   this.expenditureEconomicList = resArray[5]['records']
    //   this.expenditureFiscalList = resArray[6]['records']
    //   this.expenditureSubjectList = resArray[7]['records']
    //   this.expenditureKpiList = resArray[8]['records']
    // },
    getList() {
      this.listLoading = true
      this.listQuery.quotaDateStart = ''
      this.listQuery.quotaDateEnd = ''
      if (this.listQuery.quotaDateRange) {
        this.listQuery.quotaDateStart = this.listQuery.quotaDateRange[0]
        this.listQuery.quotaDateEnd = this.listQuery.quotaDateRange[1]
      }
      doGet(this.svc, '/expenditure-init-quota/page', this.listQuery).then(res => {
        this.listLoading = false
        this.list = res['records']
        this.total = parseInt(res['total'])
      }).catch(e => {
        console.error(e)
        this.listLoading = false
      })
    },
    handleResetQuery() {
      this.resetForm("listQuery")
      this.listQuery.quotaDateStart = ''
      this.listQuery.quotaDateEnd = ''
      this.listQuery.quotaDateRange = []
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    handleSelectionChange(data) {
      this.selectionList = data
    },
    handleSortChange(data) {
      const { prop, order } = data
      this.listQuery.sortField = prop
      this.listQuery.sortType = order === 'ascending' ? 'asc' : 'desc'
      this.handleFilter()
    },
    handleEdit(row) {
      this.goTargetByName('expenditureInitQuotaEdit', {id: row.id, oper: 'edit'})
    },
    handleView(row) {
      this.goTargetByName('expenditureInitQuotaEdit', {id: row.id, oper: 'view'})
    },
    handleAdd() {
      this.goTargetByName('expenditureInitQuotaEdit', {oper: 'add'})
    },
    handleExport() {
      doGetDownload(this.svc, '/expenditure-init-quota/export', this.listQuery)
    },
    handleDelete(row) {
      doDelete(this.svc, '/expenditure-init-quota/' + row.id, {}).then(_ => {
        notifySuccess('操作成功')
        this.getList()
      })
    },
    async doConfirm(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      if (this.dialogType === 'edit') {
        doPut(this.svc, '/expenditure-init-quota/modify', this.obj).then(() => {
          notifySuccess('修改成功')
          this.getList()
          this.dialogVisible = false
        })
      } else if (this.dialogType === 'add') {
        doPost(this.svc, '/expenditure-init-quota/add', this.obj).then(() => {
          notifySuccess('新增成功')
          this.getList()
          this.dialogVisible = false
        })
      }
    }
  }
}
</script>
